package com.baichuan.util;

/**
 * @Auther: leo
 * @Date: 2021/9/11 22:05
 * @Description:
 */

import com.alibaba.fastjson.JSONObject;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class TencentOcrUtil {

    private static String secretId = "AKIDKTMzLPEn56tUwCLFtGOFp89uOJxLTKuD";
    private static String secretKey = "4sPfeLmwpRmqeaJn20jojPpzvd7ZqiRM";
    private static String endoiont = "ocr.tencentcloudapi.com";
    private static String region = "ap-shanghai";

    /**
     * 车驾号识别
     *
     * @param imageBase64 demo:{"Vin":"LBVTZ4101LSU66289","RequestId":"51a5f938-7c9e-412f-93b6-e30b2e00d233"}
     */
    public static JSONObject vin(String imageBase64, String imageUrl) {
        JSONObject result = new JSONObject();
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint(endoiont);
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            OcrClient client = new OcrClient(cred, region, clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            VinOCRRequest req = new VinOCRRequest();
            req.setImageBase64(imageBase64);
            req.setImageUrl(imageUrl);
            VinOCRResponse resp = client.VinOCR(req);
            result.put("resp", resp);
            result.put("requestId", resp.getRequestId());
        } catch (TencentCloudSDKException e) {
            result.put("errorCode", e.getErrorCode());
            result.put("errorMsg", e.getMessage());
            result.put("requestId", e.getRequestId());
        }
        return result;
    }

    public static String encryptToBase64(String filePath) {
        if (filePath == null) {
            return null;
        }
        try {
            byte[] b = Files.readAllBytes(Paths.get(filePath));
            return Base64.getEncoder().encodeToString(b);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 机动车登记证书
     *
     * @param imageBase64 demo: {"VehicleRegCertInfos":[{"Name":"机动车所有人1","Value":"许斌"},{"Name":"身份证明名称1","Value":"居民身份证"},{"Name":"号码1","Value":"43048119841004373X"},{"Name":"机动车所有人2","Value":"朱鹏飞"},{"Name":"身份证明名称2","Value":"居民身份证"},{"Name":"号码2","Value":"330721199102057110"},{"Name":"车辆型号","Value":"BMW6475CX"},{"Name":"车辆识别代号/车架号","Value":"LBVTZ4101LSU66289"},{"Name":"发动机号","Value":"4291E821"},{"Name":"制造厂名称","Value":"华晨宝马汽车有限公司"},{"Name":"编号","Value":"*43001346804*"},{"Name":"登记机关1","Value":"湖南省邵阳市公安局交通巡逻警察"},{"Name":"登记日期1","Value":"2019-10-28"},{"Name":"机动车登记编号1","Value":"湘DLS986"},{"Name":"登记机关2","Value":"金华市公安局交警支队车管所"},{"Name":"登记日期2","Value":"2021-01-21"},{"Name":"机动车登记编号2","Value":"浙G7Y0V1"},{"Name":"使用性质","Value":"非营运"},{"Name":"车辆获得方式","Value":"购买"},{"Name":"车辆出厂日期","Value":"2019-09-24"},{"Name":"发证日期","Value":"2019-10-28"},{"Name":"燃料种类","Value":"汽油"},{"Name":"车辆类型","Value":"小型普通客车"},{"Name":"国产/进口","Value":"国产"},{"Name":"车辆品牌","Value":"宝马牌"},{"Name":"车身颜色","Value":"白"},{"Name":"发动机型号","Value":"B48B20C"},{"Name":"转向形式","Value":"方向盘"},{"Name":"轮胎数","Value":"4"},{"Name":"轴距","Value":"2864mm"},{"Name":"轴数","Value":"2"},{"Name":"外廓尺寸","Value":"长4717宽1891高1689mm"},{"Name":"总质量","Value":"2385kg"}],"RequestId":"1bd5912d-cb1d-445f-b39c-11aba69350cf"}
     */
    public static JSONObject vehicleRegCert(String imageBase64, String imageUrl) {
        JSONObject result = new JSONObject();
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint(endoiont);
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            OcrClient client = new OcrClient(cred, region, clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            VehicleRegCertOCRRequest req = new VehicleRegCertOCRRequest();
            req.setImageBase64(imageBase64);
            req.setImageUrl(imageUrl);
            VehicleRegCertOCRResponse resp = client.VehicleRegCertOCR(req);
            result.put("resp", resp);
            result.put("requestId", resp.getRequestId());
        } catch (TencentCloudSDKException e) {
            result.put("errorCode", e.getErrorCode());
            result.put("errorMsg", e.getMessage());
            result.put("requestId", e.getRequestId());
        }
        return result;
    }

    /**
     * 行驶证
     *
     * @param imageBase64 demo: {"FrontInfo":{"PlateNo":"桂AN16C5","VehicleType":"小型轿车","Owner":"苏千玲","Address":"广西合浦县白沙镇榄根村委会沙岗铺村11号","UseCharacter":"非营运","Model":"东风日产牌DFL7203VAK2","Vin":"LGBF5AE08DR067921","EngineNo":"854907T","RegisterDate":"2014-03-06","IssueDate":"2021-09-07","Seal":"广西壮族自治区南宁市公安局交通警察支队"},"RecognizeWarnCode":[],"RecognizeWarnMsg":[],"RequestId":"e203de35-0768-4a68-aba9-564f7b0c4cd0"}
     *                    <p>
     *                    demo: {"BackInfo":{"PlateNo":"桂AN16C5","FileNo":"450106221458","AllowNum":"5人","TotalMass":"1870kg","CurbWeight":"1458kg","LoadQuality":"--","ExternalSize":"4868×1830×1490mm","Marks":"","Record":"检验有效期至2022年03月桂A汽油","TotalQuasiMass":"--"},"RecognizeWarnCode":[],"RecognizeWarnMsg":[],"RequestId":"12288d7e-492a-4857-b690-7a8240d9cc2c"}
     */
    public static JSONObject vehicleLicense(String imageBase64, String imageUrl) {
        JSONObject result = new JSONObject();
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint(endoiont);
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            OcrClient client = new OcrClient(cred, region, clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            VehicleLicenseOCRRequest req = new VehicleLicenseOCRRequest();
            /*String base64Str = encryptToBase64("E:\\project\\qqm\\carSource\\测试文件\\车型不完整行驶证.png");
            req.setImageBase64(base64Str);
            req.setImageUrl(null);*/
            req.setImageBase64(imageBase64);
            req.setImageUrl(imageUrl);
            //行驶证的 FRONT 为行驶证主页正面（有红色印章的一面）， BACK 为行驶证副页正面（有号码号牌的一面）。 默认值为：FRONT。
            req.setCardSide("FRONT");
            VehicleLicenseOCRResponse resp = client.VehicleLicenseOCR(req);
            result.put("resp", resp);
            result.put("requestId", resp.getRequestId());
        } catch (TencentCloudSDKException e) {
            result.put("errorCode", e.getErrorCode());
            result.put("errorMsg", e.getMessage());
            result.put("requestId", e.getRequestId());
        }
        return result;
    }

    /**
     * 身份证识别
     *
     * @param imageBase64
     *
     * api文档：https://cloud.tencent.com/document/api/866/33524
     *
     * 人像面：{"address":"河南省潢川县传流店乡王营村何老营组","advancedInfo":"{}","authority":"","birth":"1991/10/28","idNum":"411526199110285422","name":"何保红","nation":"汉","requestId":"8fa3c69d-2cb7-4436-9ea6-c6ebf1284219","sex":"女","validDate":""}
     *
     * 国徽面：{"address":"","advancedInfo":"{}","authority":"潢川县公安局","birth":"","idNum":"","name":"","nation":"","requestId":"b1d8acb3-4f8d-42a6-9b5b-3e0e51731067","sex":"","validDate":"2010.01.27-2020.01.27"}
     */
    public static JSONObject idCardOCR(String imageBase64, String imageUrl) {
        JSONObject result = new JSONObject();
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint(endoiont);
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            OcrClient client = new OcrClient(cred, region, clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            IDCardOCRRequest req = new IDCardOCRRequest();
            req.setImageBase64(imageBase64);
            req.setImageUrl(imageUrl);

            //FRONT：身份证有照片的一面（人像面），
            //BACK：身份证有国徽的一面（国徽面），
            //该参数如果不填，将为您自动判断身份证正反面。
            //req.setCardSide("");
            IDCardOCRResponse resp = client.IDCardOCR(req);
            result.put("resp", resp);
            result.put("requestId", resp.getRequestId());
        } catch (TencentCloudSDKException e) {
            result.put("errorCode", e.getErrorCode());
            result.put("errorMsg", e.getMessage());
            result.put("requestId", e.getRequestId());
        }
        return result;
    }


    /**
     * 营业执照
     *
     * api文档：https://cloud.tencent.com/document/api/866/36215
     *
     * @param imageBase64
     * @param imageUrl
     *
     * @return
     */
    public static JSONObject bizLicenseOCR(String imageBase64, String imageUrl) {
        JSONObject result = new JSONObject();
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint(endoiont);
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            OcrClient client = new OcrClient(cred, region, clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            BizLicenseOCRRequest req = new BizLicenseOCRRequest();
            req.setImageBase64(imageBase64);
            req.setImageUrl(imageUrl);

            BizLicenseOCRResponse resp = client.BizLicenseOCR(req);
            result.put("resp", resp);
            result.put("requestId", resp.getRequestId());
        } catch (TencentCloudSDKException e) {
            result.put("errorCode", e.getErrorCode());
            result.put("errorMsg", e.getMessage());
            result.put("requestId", e.getRequestId());
        }
        return result;
    }

    public static void main(String[] args) {
        //String base64Str = encryptToBase64("E:\\project\\qqm\\carSource\\测试文件\\vin.png");
        //String base64Str = encryptToBase64("E:\\project\\qqm\\carSource\\测试文件\\注册登记证书.png");
        //vin(base64Str);

        /*String base64Str = encryptToBase64("E:\\project\\qqm\\carSource\\测试文件\\车型不完整行驶证.png");
        System.out.println(base64Str);
        //System.out.println(vehicleLicense(base64Str, null));*/
        //System.out.println(idCardOCR(null, "https://zzsourcecar.oss-cn-hangzhou.aliyuncs.com/banner/220323/c7ad926cebce48868148ece1851ef776o.jpg?Expires=3229165231&OSSAccessKeyId=LTAI4GBcZtMnrVQ72WG22fri&Signature=gsS%2B2ZGYwosq6GHUVe%2FiHhWCdYc%3D"));
        //System.out.println(idCardOCR(null, "https://zzsourcecar.oss-cn-hangzhou.aliyuncs.com/banner/220323/205c78eb8cea46e78e47ef7320091671o.jpg?Expires=3229165357&OSSAccessKeyId=LTAI4GBcZtMnrVQ72WG22fri&Signature=qKv2ZhWdQ8QT5ZCD8a1fMuDghpE%3D"));
        //String base64Str = encryptToBase64("E:\\project\\qqm\\carSource\\测试文件\\注册登记证书.png");
        //vehicleRegCert(base64Str);
    }
}
